//
//  QuickLoansView.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/11/9.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit

@objc protocol QuickLoansViewDelegate {
    
    @objc optional func quickLoanApplication() //快速贷款申请
}

class QuickLoansView: UIView {
    
    weak var delegate : QuickLoansViewDelegate?
    
    fileprivate var sounds = 60 //秒
    fileprivate var timer :  Timer! //计时器
    
    let phoneTextView = UITextField.init(Width: 10)
    let codeTextView = UITextField.init(Width: 10)
    fileprivate let codeButton = UIButton() //验证码
 
    init() {
        super.init(frame: .zero)
        
        self.layer.contents = UIImage.init(named: "quick_loan")?.cgImage
        let lineY:CGFloat = ScreenW/1.11 * 410/675 //线条位置
        
//        let titleLabel = UILabel()
//        titleLabel.text = quickLoans
//        titleLabel.font = UIFont.boldSystemFont(ofSize: RATIO(maxNum: 25))
//        self.addSubview(titleLabel)
        
        let lineView = UIView()
        self.addSubview(lineView)
        
        
        phoneTextView.keyboardType = .numberPad
        phoneTextView.placeholder = inputPhoneNumebr
        self.addSubview(phoneTextView)
        
        codeButton.setTitle(getCode, for: .normal)
        codeButton.setTitleColor(UIColor.red, for: .normal)
        codeButton.titleLabel?.font = UIFont.systemFont(ofSize: RATIO(maxNum: 16))
        codeButton.addTarget(self, action: #selector(getCodeAction), for: .touchUpInside)
        self.addSubview(codeButton)
        
        codeTextView.placeholder = inputCode
        self.addSubview(codeTextView)
        
        let applyButton = UIButton()
        applyButton.backgroundColor = UIColor.applicationColor()
        applyButton.setTitle(applyNow, for: .normal)
        applyButton.setTitleColor(UIColor.black, for: .normal)
        applyButton.titleLabel?.font = UIFont.systemFont(ofSize: RATIO(maxNum: 16))
//        applyButton.layer.cornerRadius = 5
//        applyButton.layer.masksToBounds = true
        applyButton.addTarget(self, action: #selector(toApplication), for: .touchUpInside)
        self.addSubview(applyButton)
        
        phoneTextView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(RATIO(maxNum: 40))
            make.right.equalToSuperview().offset(RATIO(maxNum: -40))
            make.top.equalToSuperview().offset(lineY-RATIO_H(maxNum: 40))
            make.height.equalTo(RATIO_H(maxNum: 40))
        }
        
//        titleLabel.snp.makeConstraints { (make) in
//            make.bottom.equalTo(phoneTextView.snp.top).offset(RATIO_H(maxNum: -5))
//            make.centerX.equalToSuperview()
//            make.height.equalTo(RATIO_H(maxNum: 30))
//            make.width.greaterThanOrEqualTo(10)
//        }
        
        codeButton.snp.makeConstraints { (make) in
            make.right.equalTo(phoneTextView)
            make.top.equalTo(phoneTextView.snp.bottom).offset(RATIO_H(maxNum: 10))
            make.height.equalTo(phoneTextView)
            make.width.equalTo(RATIO(maxNum: 100))
        }
        
        codeTextView.snp.makeConstraints { (make) in
            make.top.height.equalTo(codeButton)
            make.right.equalTo(codeButton.snp.left)
            make.left.equalTo(phoneTextView)
        }
        
        applyButton.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.width.equalTo(RATIO(maxNum: 150))
        make.top.equalTo(codeTextView.snp.bottom).offset(RATIO_H(maxNum: 20))
            make.height.equalTo(RATIO_H(maxNum: 40))
        }
        
    }
    
    //MARK: 获取验证码
    @objc fileprivate func getCodeAction() {
        
        if phoneTextView.text == "" {
            KMTool.showText(_text: inputPhone)
            return
        }
        
        KMTool.requestMethod(.post, URLString: url_signInCode, parameters: ["user_name":phoneTextView.text!], success: { (value, json) in
            
            if json["status"].stringValue == "0" {
                
                self.codeButton.isEnabled = false
                self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.waitForCode(sender:)), userInfo: nil, repeats: true)
                //添加至子线程
                RunLoop.main.add(self.timer, forMode: .commonModes)
            }
            
            KMTool.showText(_text: json["msg"].stringValue)
           
        }) {
            
        }
        
    }
    
    //MARK: 等待验证码
    @objc fileprivate func waitForCode(sender:Timer) {
        
        sounds -= 1
        codeButton.setTitle("\(sounds)", for: .normal)
        
        if sounds == 0 {
            clearTime()
        }
    }
    
    //MARK: 清除计时器
    func clearTime() {
        
        if timer != nil {
            sounds = 60
            codeButton.isEnabled = true
            codeButton.setTitle(getCode, for: .normal)
            timer.invalidate()
            timer = nil
        }
    }
    
    //MARK: 验证码验证
    @objc fileprivate func toApplication() {
        
        if phoneTextView.text == "" {
            KMTool.showText(_text: inputPhone)
            return
        }
        
        if codeTextView.text == "" {
            KMTool.showText(_text: inputCode)
            return
        }
        
        KMTool.waiting()
        
        KMTool.requestMethod(.get, URLString: url_bindPhoneCode, parameters: ["psw":"kameng98_loan","phone":phoneTextView.text!,"code":codeTextView.text!], success: { (value, json) in
            
            KMTool.stop()
            
            if json["status"].stringValue == "0"{//验证码正确
                self.applyNowAction()
            }else{
                KMTool.showText(_text: json["msg"].stringValue)
            }
            
            
        }) {
            
            KMTool.stop()
        }
    }
    
    //MARK: 立即申请
    fileprivate func applyNowAction() {
        
        KMTool.requestGetData(URLString: url_quickLoanNews, parameters: ["psw":"kameng98_loan","phone":phoneTextView.text!], success: { (data) in
            
            self.delegate?.quickLoanApplication!()
            
        }) {
            
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
